from django.http import JsonResponse, Http404

# Create your views here.
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import status, mixins, generics, viewsets, filters
from rest_framework.decorators import api_view
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from article.models import Article, Category, Tag, Avatar
from article.permissions import IsAdminUserOrReadOnly
from article.serializers import ArticleSerializer, CategorySerializer, CategoryDetailSerializer, TagSerializer, \
    ArticleDetailSerializer, AvatarSerializer


##############################################################################################
class ArticleViewSet(viewsets.ModelViewSet):
    """文章视图集"""
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    permission_classes = [IsAdminUserOrReadOnly]

    # 模糊匹配
    filter_backends = [filters.SearchFilter, ]  # xxxxx/?search=xxx
    # filter_backends = [DjangoFilterBackend,]
    search_fields = ['title']

    def perform_create(self, serializer):
        serializer.save(author=self.request.user)

    def get_serializer_class(self):
        if self.action == 'list':
            return ArticleSerializer
        else:  # 详情，显示 渲染好的中文和目录
            return ArticleDetailSerializer


class CategoryViewSet(viewsets.ModelViewSet):
    """分类视图集"""
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    permission_classes = [IsAdminUserOrReadOnly]

    def get_serializer_class(self):
        if self.action == 'list':
            return CategorySerializer
        else:
            return CategoryDetailSerializer


class TagViewSet(viewsets.ModelViewSet):
    """标签视图集"""
    queryset = Tag.objects.all()
    serializer_class = TagSerializer
    permission_classes = [IsAdminUserOrReadOnly]


class AvatarViewSet(viewsets.ModelViewSet):
    queryset = Avatar.objects.all()
    serializer_class = AvatarSerializer
    permission_classes = [IsAdminUserOrReadOnly]



###########################
# @api_view(['GET', 'POST'])
# def article_list(request):
#     if request.method == 'GET':
#         articles = Article.objects.all()
#         serializer = ArticleSerializer(instance=articles, many=True)
#         return Response(serializer.data)
#     elif request.method == 'POST':
#         serializer = ArticleSerializer(data=request.data)
#         if serializer.is_valid():
#             serializer.save()
#             return Response(serializer.data, status=status.HTTP_201_CREATED)
#         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


#########################################################################################################
# class ArticleList(mixins.ListModelMixin,
#                   mixins.CreateModelMixin,
#                   generics.GenericAPIView):
#     """文章列表"""
#     queryset = Article.objects.all()
#     serializer_class = ArticleSerializer
#     permission_classes = [IsAdminUserOrReadOnly]
#
#     def get(self, request, *args, **kwargs):
#         return self.list(request, *args, **kwargs)
#
#     def post(self, request, *args, **kwargs):
#         return self.create(request, *args, **kwargs)
#
#     def perform_create(self, serializer):
#         serializer.save(author=self.request.user)  # author字段----外键保存信息
#
#
# class ArticleDetail(mixins.RetrieveModelMixin,
#                     mixins.UpdateModelMixin,
#                     mixins.DestroyModelMixin,
#                     generics.GenericAPIView):
#     """文章详情"""
#     #############################   使用Mixins的方法   #############################
#     queryset = Article.objects.all()
#     serializer_class = ArticleDetailSerializer
#     permission_classes = [IsAdminUserOrReadOnly]
#
#     def get(self, request, *args, **kwargs):
#         return self.retrieve(request, *args, **kwargs)
#
#     def put(self, request, *args, **kwargs):
#         return self.update(request, *args, **kwargs)
#
#     def delete(self, request, *args, **kwargs):
#         return self.destroy(request, *args, **kwargs)
#
#     #############################   自己写的版本   #################################
#     # def get_object(self, pk):
#     #     """获取单个文章对象"""
#     #     try:
#     #         return Article.objects.get(pk=pk)
#     #     except:
#     #         raise Http404
#     #
#     # def get(self, request, pk):
#     #     article = self.get_object(pk)
#     #     serializer = ArticleDetailSerializer(instance=article)
#     #     return Response(serializer.data)
#     #
#     # def put(self, request, pk):
#     #     article = self.get_object(pk)
#     #     serializer = ArticleDetailSerializer(data=request.data, instance=article)
#     #     if serializer.is_valid():
#     #         serializer.save()
#     #         return Response(serializer.data)
#     #     return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
#     #
#     # def delete(self, request, pk):
#     #     article = self.get_object(pk)
#     #     article.delete()
#     #     return Response(status=status.HTTP_204_NO_CONTENT)
